package com.xiaoyu.cloud;

/**
 * @author zgb
 * @desc ...
 * @date 2023-08-07 19:32:51
 */


import cn.hutool.json.JSONUtil;

import com.xiaoyu.common.core.enums.ResultCodeEnum;
import com.xiaoyu.common.core.exception.RException;
import com.xiaoyu.common.core.result.R;
import feign.Response;
import feign.Util;
import feign.codec.ErrorDecoder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Objects;

/**
 * 解决Feign的异常包装，统一返回结果
 *
 * @author 公众号：JAVA日知录
 */
@Slf4j
public class OpenFeignErrorDecoder implements ErrorDecoder {
    /**
     * Feign异常解析
     *
     * @param methodKey 方法名
     * @param response  响应体
     * @return BizException
     */
    @Override
    public Exception decode(String methodKey, Response response) {
        log.error("feign client error,response is {}:", response);

        //获取数据
        try {
            String errorContent = IOUtils.toString(response.body().asInputStream());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        String body = null;
        try {
            body = Util.toString(response.body().asReader(Charset.defaultCharset()));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        R r = JSONUtil.toBean(body, R.class);
        if (!Objects.equals(r.getCode(), ResultCodeEnum.SUCCESS.getCode())) {
            return new RException(r.getMsg(), r.getCode());
        }


        return new RuntimeException("Feign client 调用异常");
    }
}
